package com.quzi.kettle.activitise.process;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.example.httprequest.AsyncBean;
import com.example.httprequest.AsyncHttpUtilClient;
import com.github.mikephil.charting.utils.FileUtils;
import com.loopj.android.http.RequestParams;
import com.quzi.kettle.MyApplication;
import com.quzi.kettle.R;
import com.quzi.kettle.activitise.BaseActivity;
import com.quzi.kettle.activitise.main.MainActivityTest;
import com.quzi.kettle.activitise.main.TempActivity;
import com.quzi.kettle.api.response.DeviceListResponse;
import com.quzi.kettle.api.response.LoginResponse;
import com.quzi.kettle.bean.http.KettleDevice;
import com.quzi.kettle.bean.http.User;
import com.quzi.kettle.utils.MSharePerference;
import com.quzi.kettle.view.ImageEditText;
import com.quzi.kettle.view.ImageEditorInterface;
import com.quzi.kettle.view.TitleBarView;

public class LoginActivity extends BaseActivity implements OnClickListener {

	ImageEditText username;
	ImageEditText password;
	TitleBarView titleView;
	CheckBox autoLogin;

	private boolean isCheck = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_login);

		autoLogin = (CheckBox) findViewById(R.id.checkauto);
		autoLogin.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean isCheck) {
				LoginActivity.this.isCheck = isCheck;
			}
		});

		findViewById(R.id.register).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
		findViewById(R.id.forgetpsw).setOnClickListener(this);

		username = (ImageEditText) findViewById(R.id.username);
		password = (ImageEditText) findViewById(R.id.password);

		username.setHint(getResources().getString(R.string.phone_number));
		password.setHint(getResources().getString(R.string.password));

		username.update_image(R.drawable.username);
		password.update_image(R.drawable.passcode);

		password.setInfoText(getResources().getString(R.string.forgetpassword));
		password.setInfoClickListener(new ImageEditorInterface() {

			@Override
			public void onInfoTextClicked() {
				// TODO Auto-generated method stub
				nextActivity(ForgetPasswordActivity.class);
			}
		});

		initTitleBar();
		password.getEditText().setInputType(
				InputType.TYPE_CLASS_TEXT
						| InputType.TYPE_TEXT_VARIATION_PASSWORD);
		username.setText(MSharePerference.getInstance(getApplicationContext())
				.get("username"));
		if (MSharePerference.getInstance(getApplicationContext()).getBoolean(
				"isCheck")) {
			autoLogin.setChecked(true);
			password.setText(MSharePerference.getInstance(
					getApplicationContext()).get("password"));
			findViewById(R.id.login).performClick();
		}
//		username.setText(MSharePerference.getInstance(getApplicationContext())
//				.get("username"));
//		if (MSharePerference.getInstance(getApplicationContext()).getBoolean(
//				"isCheck")) {
//			autoLogin.setChecked(true);
//			password.setText(MSharePerference.getInstance(
//					getApplicationContext()).get("password"));
//			findViewById(R.id.login).performClick();
//		}

	}

	@Override
	protected void initTitleBar() {
		// TODO Auto-generated method stub
		super.initTitleBar();
		titleView = (TitleBarView) findViewById(R.id.titlebar);
		titleView.setLeftIconVisible(false);
		titleView.setTitle(getResources().getString(R.string.login));
	}

	@Override
	protected void onResume() {
		super.onResume();
		password.getEditText().setInputType(
				InputType.TYPE_CLASS_TEXT
						| InputType.TYPE_TEXT_VARIATION_PASSWORD);
		username.setText(MSharePerference.getInstance(getApplicationContext())
				.get("username"));
		

	};

	private long lastTime = 0;// 提供一个变量来记录上一次按下的时间

	private void exit() {
		// 得到当前的系统时间（毫秒）
		long time = System.currentTimeMillis();
		if (time - lastTime > 2000) { // 如果两次时间太过长，大于2秒，那就不要退出，提示需要再按一次
			showTextToast(getResources().getString(R.string.main_confirm_exit));

		} else {// 如果两按下的时间是两秒内，则退出
			com.quzi.kettle.activitise.added.ActivityManager.getInstance()
					.exit();
			// 如果用户是第一次按，则将当前的时间保存为上一次按的时间，这样用户再按一下就可以退出了

		}
		lastTime = time;
	}

	/**
	 * 点击返回按键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {// 如果按下的是回退健
			// 表示按下回退键且不是常按
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& event.getRepeatCount() == 0) {
				exit();
				// 调用上面写的退出

				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	String userName, passWord;

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.register:
			nextActivity(RegisterActivity.class);
		case R.id.login:

			userName = username.getText().trim();
			passWord = password.getText().trim();

			if (userName.isEmpty()) {
				UIHandler.obtainMessage(TOASTMSG, "请输入用户名").sendToTarget();
				return;
			}
			if (passWord.isEmpty()) {
				UIHandler.obtainMessage(0, "请输入密码").sendToTarget();
				return;
			}

			MSharePerference.getInstance(getApplicationContext())
					.updateBoolean("isCheck", isCheck);
			if (isCheck) {
				MSharePerference.getInstance(getApplicationContext()).update(
						"username", userName);
				MSharePerference.getInstance(getApplicationContext()).update(
						"password", passWord);
			}
			// MSharePerference.getInstance(getApplicationContext()).delete("username");
			// MSharePerference.getInstance(getApplicationContext()).delete("password");

			if (!isShowingDialog()) {
				showLoadingDialog();
			}
			Map<String, String> loginMap = new HashMap<String, String>();
			loginMap.put("phone_number", userName);
			loginMap.put("password", passWord);
			AsyncHttpUtilClient.request(
					getApplicationContext(),
					new AsyncBean(AsyncHttpUtilClient.POST, MyApplication.url
							+ MyApplication.requestMap
									.get(MyApplication.USER_LOGIN), null,
							new RequestParams(loginMap)),
					new LoginResponse<User>() {

						@Override
						public void onSuccess(User t) {
							try {
								MyApplication.RECORD = t.getRecord();
								currUser = t;
							} catch (Exception e) {
								e.printStackTrace();
							}
							MyApplication.UUID = t.getUuid();
							MyApplication.header = new HashMap<String, String>();
							MyApplication.header.put(MyApplication.record,
									MyApplication.RECORD);

							AsyncHttpUtilClient
									.request(
											getApplicationContext(),
											new AsyncBean(
													AsyncHttpUtilClient.GET,
													MyApplication.url
															+ MyApplication.requestMap
																	.get(MyApplication.DEVICE_LIST),
													MyApplication.header, null),
											new DeviceListResponse<List<KettleDevice>>() {

												@Override
												public void onSuccess(List t) {
													// TODO Auto-generated
													// method stub
													hideSoftInput();
													dissLoadingDialog();
													deviceList = t;
//													KettleDevice virtualDevice = new KettleDevice();
//													virtualDevice
//															.setMain_mac("aabbccddeeff");
//													virtualDevice
//															.setName("虚拟水壶");
//													virtualDevice
//															.setOnline(true);
//													deviceList.add(0,
//															virtualDevice);
													if (t.isEmpty()) {
														nextActivity(TempActivity.class);
													} else {
														nextActivity(MainActivityTest.class);
														currDevice = (KettleDevice) t
																.get(0);
													}
												}

												@Override
												public void onFailure(int arg0,
														String arg1) {
													dissLoadingDialog();
												}
											});
						}

						@Override
						public void onFailure(int arg0, String arg1) {
							dissLoadingDialog();
							UIHandler.obtainMessage(
									TOASTMSG,
									getResources().getText(
											R.string.login_failed))
									.sendToTarget();
							;
						}

					});

			break;

		}
	}
}
